import app from "@/constants/app";
import { IHttpResponse, IObject } from "@/types/interface";
import router from "@/router";
import axios, { AxiosRequestConfig } from "axios";
import qs from "qs";
import { getToken } from "./cache";
import { getValueByKeys } from "./utils";
import { ElMessage } from "element-plus";
import { getAppServerTimestamp } from "@/utils/timeSync";
import { rsaEncryptBase64 } from "@/utils/encryptor";
import { APP_VERSION_APP, APP_VERSION_HEADER_NAME, RSA_PUBLIC_KEY, SIGN_ENABLED, SIGN_HEADER_NAME } from "@/constants/signature";
import { buildPlain, getSignedPath, setSignHeaders, shouldSkipSign } from "@/utils/signature";
import { isTokenError, getTokenErrorMessage } from "@/constants/tokenStatus";
import { useAppStore } from "@/store";
// console.log('VITE_APPappApi，baseURL 的值是:', app.appApi);
const http = axios. create({
  baseURL: app.appApi,
  timeout: app.requestTimeout
});

// 仅开发环境打印 baseURL，便于排查代理与环境变量
// if ((import.meta as any).env?.DEV) {
//   // eslint-disable-next-line no-console
//   console.log("App API baseURL:", (http.defaults as any)?.baseURL);
// }

http.interceptors.request.use(
  async function (config: any) {
    config.headers["X-Requested-With"] = "XMLHttpRequest";
    config.headers["Request-Start"] = new Date().getTime();
    const token = getToken();
    if (typeof token === "string" && token) {
      config.headers["token"] = token;
      // 同时附带标准授权头，部分网关只识别 Authorization
      config.headers["Authorization"] = `Bearer ${token}`;
    }
    // 注入版本号头，避免因未开启签名而缺失（同时兼容 appVersion 与 WebVersion）
    (config.headers as any)[APP_VERSION_HEADER_NAME] = APP_VERSION_APP;
    (config.headers as any)["appVersion"] = APP_VERSION_APP;
    // 签名注入（骨架）：默认根据开关与白名单决定是否附加
    try {
      if (!shouldSkipSign(config)) {
        // 对 UAT 的 TDengine 接口（/as/tdengine/**）关闭 baseURL 前缀参与签名，
        // 防止开发代理的 /v2 重写导致验签路径不一致；其他接口保持原有逻辑。
        const urlStr = String(config.url || "");
        if (urlStr.startsWith("/as/tdengine")) {
          (config as any).__signUseBasePrefix = false;
        }
        const path = getSignedPath(config);
        // 严格使用后端时间戳，获取失败直接抛错
        // 仅走 App 端时间戳接口：/as/platform/time
        const timestamp = await getAppServerTimestamp();
        const plain = buildPlain(APP_VERSION_APP, path, timestamp);
        // 便于对拍（仅开发环境启用，通过 SIGN_DEBUG 决定是否透传）
        (config as any).__plain_for_debug = plain;
        // 仅在存在公钥且启用时处理
        if (SIGN_ENABLED && RSA_PUBLIC_KEY) {
          const sign = rsaEncryptBase64(plain, RSA_PUBLIC_KEY);
          setSignHeaders(config, sign, timestamp, APP_VERSION_APP);
        }
      }
    } catch (e) {
      // 避免签名异常阻断正常请求
      console.warn("sign inject skipped:", e);
    }
    
    if (config.method?.toUpperCase() === "GET") {
      config.params = { ...config.params, _t: new Date().getTime() };
    }
    if (Object.values(config.headers).includes("application/x-www-form-urlencoded")) {
      config.data = qs.stringify(config.data);
    }
    return config;
  },
  function (error) {
    return Promise.reject(error);
  }
);
http.interceptors.response.use(
  (response) => {
    // 响应成功 - 兼容多种成功状态
    const isSuccess = 
      response.data.code === 0 || 
      response.data.code === 200 || 
      response.data.success === true ||
      response.status >= 200 && response.status < 300;
    
    if (isSuccess) {
      return response;
    }

    // 业务错误处理
    const errorMsg = response.data.msg || response.data.message || "请求失败";
    
    // 特殊错误码处理
    if (response.data.code === 401) {
      redirectLogin();
      return Promise.reject(new Error("未授权，请重新登录"));
    }
    
    if (response.data.code === 403) {
      ElMessage.error("权限不足");
      return Promise.reject(new Error("权限不足"));
    }

    // Token状态码处理
    if (isTokenError(response.data.code)) {
      const tokenErrorMsg = getTokenErrorMessage(response.data.code);
      console.log('检测到Token状态码:', response.data.code, '错误信息:', tokenErrorMsg);
      ElMessage.error(tokenErrorMsg);
      redirectLogin();
      return Promise.reject(new Error(tokenErrorMsg));
    }

    // 通用错误提示
    ElMessage.error(errorMsg);
    return Promise.reject(new Error(errorMsg));
  },
  (error) => {
    const status = getValueByKeys(error, "response.status", 500);
    const httpCodeLabel: IObject<string> = {
      400: "请求参数错误",
      401: "未授权，请登录",
      403: "拒绝访问",
      404: `请求地址出错: ${getValueByKeys(error, "response.config.url", "")}`,
      408: "请求超时",
      500: "API接口报500错误",
      501: "服务未实现",
      502: "网关错误",
      503: "服务不可用",
      504: "网关超时",
      505: "HTTP版本不受支持"
    };
    if (error && error.response) {
      console.error("请求错误", error.response.data);
    }
    if (status === 401) {
      redirectLogin();
    }
    return Promise.reject(new Error(httpCodeLabel[status] || "接口错误"));
  }
);

const redirectLogin = () => {
  try {
    // 清除用户状态和token
    const appStore = useAppStore();
    appStore.logout();
    
    // 跳转到登录页
    router.replace("/login");
    
    console.log('用户已登出，跳转到登录页');
  } catch (error) {
    console.error('登出过程中发生错误:', error);
    // 即使发生错误也要跳转到登录页
    router.replace("/login");
  }
};

export default (o: AxiosRequestConfig): Promise<IHttpResponse> => {
  return new Promise((resolve, reject) => {
    http(o)
      .then((res) => {
        return resolve(res.data);
      })
      .catch(reject);
  });
};
